package com.lxc.C2DM.http;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * 发送http请求的 工具类
 * @author Shineflag
 *
 */
public class URLPost {
	/**
	 * 发送http请求
	 * @param url  请求的地址
	 * @param params  请求的参数
	 * @param header  htttp头
	 * @param timeout  超时时间
	 * @return  获取的结果
	 */
	public static String PostURL(String url,
			Map<String, String> params, Map<String,String> header,int timeout) {
		String result = null;
		HttpClient client = null;
		HttpResponse response = null;
		HttpPost postRequest = null;

		HttpParams httpParams = new BasicHttpParams(); // 创建HttpParams以用来设置HTTP参数（这一部分不是必需的）
		HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000); // 设置连接超时
		HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000); // 设置Socket超时
		HttpConnectionParams.setSocketBufferSize(httpParams, 8 * 1024); // Socket数据缓存默认8K
		HttpConnectionParams.setTcpNoDelay(httpParams, false);
		HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
		HttpClientParams.setRedirecting(httpParams, false);
		client = new DefaultHttpClient(httpParams);


		try {
			// 根据PHP情况设置超时
			client.getParams().setParameter(
					HttpConnectionParams.CONNECTION_TIMEOUT, timeout);
			client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,
					timeout);

			
			List<NameValuePair> postParams = getpostParams(params);
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
					postParams, HTTP.UTF_8);
			postRequest = new HttpPost(url);
			setHeader(postRequest, header);
			postRequest.setEntity(formEntity);
			response = client.execute(postRequest);
			int responseCode = response.getStatusLine().getStatusCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				result = EntityUtils.toString(response.getEntity());
				System.out.println("result = "+result);
			}else{
				System.out.println("responseCode ="+responseCode);
			}
		
		} catch (MalformedURLException e) {
			// 抛出这一异常指示出现了错误的 URL。或者在规范字符串中找不到任何合法协议，或者无法分析字符串
			e.printStackTrace();

		} catch (ProtocolException e) {
			// 协议故障
			
			e.printStackTrace();


		} catch (ConnectTimeoutException e) {
			
			e.printStackTrace();
		
		} catch (IOException e) {
			
			e.printStackTrace();
		}  finally {
		}

		return result;
	}

	/**
	 * 发送http请求
	 * @param url  请求的地址
	 * @param params  请求的参数
	 * @param timeout  超时时间
	 * @return
	 */
	public static String PostURL(String url,
			Map<String, String> params, int timeout) {
		String result = null;
		HttpClient client = null;
		HttpResponse response = null;
		HttpPost postRequest = null;

		HttpParams httpParams = new BasicHttpParams(); // 创建HttpParams以用来设置HTTP参数（这一部分不是必需的）
		HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000); // 设置连接超时
		HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000); // 设置Socket超时
		HttpConnectionParams.setSocketBufferSize(httpParams, 8 * 1024); // Socket数据缓存默认8K
		HttpConnectionParams.setTcpNoDelay(httpParams, false);
		HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
		HttpClientParams.setRedirecting(httpParams, false);
		client = new DefaultHttpClient(httpParams);


		try {
			// 根据PHP情况设置超时
			client.getParams().setParameter(
					HttpConnectionParams.CONNECTION_TIMEOUT, timeout);
			client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,
					timeout);


			List<NameValuePair> postParams = getpostParams(params);
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
					postParams, HTTP.UTF_8);
			postRequest = new HttpPost(url);
			postRequest.setEntity(formEntity);
			response = client.execute(postRequest);
			int responseCode = response.getStatusLine().getStatusCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				result = EntityUtils.toString(response.getEntity());
				System.out.println("result = "+result);
			}else{
				System.out.println("responseCode ="+responseCode);
			}
		
		} catch (MalformedURLException e) {
			// 抛出这一异常指示出现了错误的 URL。或者在规范字符串中找不到任何合法协议，或者无法分析字符串

		} catch (ProtocolException e) {
			// 协议故障


		} catch (ConnectTimeoutException e) {
		
		} catch (IOException e) {
		} catch (Exception e) {
		} finally {
		}

		return result;
	}
	
	/**
	 * 生成请求参数
	 * @param params 
	 * @return
	 */
	public static List<NameValuePair> getpostParams(Map<String,String> params){
		List<NameValuePair> postParams = new ArrayList<NameValuePair>(2);
		BasicNameValuePair param = null;
		for(String key:params.keySet()){
			param = new BasicNameValuePair(key, params.get(key));
			postParams.add(param);
		}
		return postParams;
	}
	
	/**
	 * 设置http头
	 * @param httpPost
	 * @param header
	 */
	private static void setHeader(HttpPost httpPost,Map<String,String> header){
		if(httpPost == null || header == null)
			return;
		for(String key:header.keySet()){
			httpPost.addHeader(key, header.get(key));
		}
		
	}

}
